import re
import os,sys
import datetime
os.chdir("./")              
sys.path.append("./lib")
import serial

def open_serial_port(port_name, baud_rate):
    try:
        ser = serial.Serial(port_name, baud_rate, timeout=1)
        return ser
    except serial.SerialException as e:
        print(f"Failed to open serial port: {e}")
        return None

def filter_and_log(serial_port, log_filename):
    with open(log_filename, 'a') as log_file:
        while True:
            try:
                line = serial_port.readline().decode('utf-8', errors='ignore').strip()
            except UnicodeDecodeError:
                # Handle decoding errors (ignore invalid bytes)
                continue

            if line:
                if 'usb' in line.lower():
                    print(line)
                    current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    log_line = f"[{current_time}] {line}"
                    print(log_line)
                    log_file.write(log_line + '\n')
                    log_file.flush()

                    
if __name__ == "__main__":
    serial_port_name = 'COM4'
    baud_rate = 1500000
    log_file_name = 'serial_log.txt'
    serial_port = open_serial_port(serial_port_name, baud_rate)
    if serial_port:
        try:
            filter_and_log(serial_port, log_file_name)
        except KeyboardInterrupt:
            print("User interrupted. Closing serial port.")
        finally:
            serial_port.close()
    else:
        print("Exiting due to serial port failure.")